package org.jradweb.tools.generator.freemarker.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jradweb.tools.generator.FileAlreadyExistsException;
import org.jradweb.tools.generator.FileOperatorException;
import org.jradweb.tools.generator.FreemarkerTemplateExcepion;

import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * 
 *
 * Created On 2008-2-29
 * @author <a href="mailto:wagzhi@gmail.com">Paul Wang</a>
 * @version $Id: FileGenerator.java 42 2008-03-05 01:15:20Z wagzhi $
 */
public class FileGenerator {

	public static boolean writeFile(File dist, Map params, Template template,
			boolean isOverWrite) throws FileOperatorException,
			FileAlreadyExistsException, FreemarkerTemplateExcepion {
		try {

			if (dist.exists()) {
				if (!dist.isFile()) {
					String msg = dist.getAbsolutePath() + " is not a file.";
					throw new FileOperatorException(msg);
				}
				if (isOverWrite) {
					dist.delete();
					dist.createNewFile();
				} else {
					String msg = dist.getAbsolutePath() + " already exists.";
					throw new FileAlreadyExistsException(msg);
				}
			} else {
				File dir=dist.getParentFile();
				if(!dir.exists())
					dir.mkdirs();
				dist.createNewFile();
			}

			FileWriter writer = new FileWriter(dist);
			template.process(params, writer);
			writer.close();
			
			return true;
		} catch (IOException e) {
			throw new FileOperatorException(e);
		} catch (TemplateException e) {
			throw new FreemarkerTemplateExcepion(e);
		}
	}
	
	public static void main(String[] args){
		try {
			File dist=new File("D:\\workspace2\\jradtest\\domainClass.java");
			Template template=Templates.MODEL_TEMPLATE;
			Map params=new HashMap();
			params.put("groupId", "com.infowarelab");
			params.put("artifactId", "test");
			params.put("modelTableName", "test_user");
			params.put("modelName", "User");
			writeFile(dist, params, template, true);
		} catch (FileOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileAlreadyExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FreemarkerTemplateExcepion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
